package com.qinghuan.threads.chapterOne;

/**
 * @Author: dubao
 * @Date: 2022/5/17 20:43
 * @Description:
 */

/**
 * 模拟死锁
 * 死锁产生的条件
 * 1、互斥条件：线程对已经获得的资源进行排他性使用，即该资源只能同时被一个线程占用。
 * 2、请求并持有条件：一个线程已经占有一个资源了，但是又提出了新的资源请求，而新资源被其他线程占用
 * 3、不可剥夺条件：线程获取到的资源在自己使用完之前不能被其他线程抢占
 * 4、环路等待条件：指在发生死锁时，必然存在一个线程一资源的环形链
 */
public class Test1_9_1 {

    //创建资源
    private static Object resourceA = new Object();
    private static Object resourceB = new Object();

    public static void main(String[] args) {
        Thread threadA = new Thread(() -> {
            synchronized (resourceA) {
                System.out.println(Thread.currentThread() + "get ResourceA");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread() + "waiting get sourceB");
                synchronized (resourceB) {
                    System.out.println(Thread.currentThread() + "get ResourceB");
                }
            }
        });

        Thread threadB = new Thread(() -> {
            synchronized (resourceB) {
                System.out.println(Thread.currentThread() + "get ResourceB");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread() + "waiting get sourceA");
                synchronized (resourceA) {
                    System.out.println(Thread.currentThread() + "get ResourceA");
                }
            }
        });

        threadA.start();
        threadB.start();

    }

}
